using UnityEngine;
using System.Collections.Generic;

public class BSPNode
{
	public BSPRectangle cellSize;
	public BSPRectangle myRoom;
	public List<BSPRectangle> childRooms;
	public BSPNode parent;
	public BSPNode[] children = new BSPNode[2];
    public BSPRectangle splitPoint;
    public BSPNode sister;
    PseudoRandom.MersenneTwister random;



    public BSPNode(BSPRectangle cellSize, PseudoRandom.MersenneTwister random)
    {
        this.random = random;
        this.cellSize = cellSize;
        childRooms = new List<BSPRectangle>();
    }

	
	public void AddRoom(BSPRectangle newRoom)
	{
        //myRoom = newRoom;
		childRooms.Add(newRoom);
		if(parent != null) parent.AddRoom(newRoom);
        
	}

    public void ClearRooms()
    {
        childRooms.Clear();
        myRoom = null;
        if (children[0] != null)
        {
            children[0].ClearRooms();
            children[1].ClearRooms();
        }
    }

    public void GenerateRoom()
    {
        BSPRectangle newRoom = new BSPRectangle(0, 0, 0, 0);

        int minXSize = (int)(cellSize.width * BSPConfig.roomFillXMin);
        int maxXSize = (int)(cellSize.width * BSPConfig.roomFillXMax);
        //need to clamp
        minXSize = Mathf.Max(3, minXSize);
        maxXSize = Mathf.Min(cellSize.width - BSPConfig.roomPad * 2, maxXSize);

        int minYSize = (int)(cellSize.height * BSPConfig.roomFillYMin);
        int maxYSize = (int)(cellSize.height * BSPConfig.roomFillYMax);
        //clamp
        minYSize = Mathf.Max(3, minYSize);
        maxYSize = Mathf.Min(cellSize.height - BSPConfig.roomPad * 2, maxYSize);

        //gen size
        int xSize = random.genrand_N(maxXSize - minXSize + 1) + minXSize;
        int ySize = random.genrand_N(maxYSize - minYSize + 1) + minYSize;

        //place room
        int minX = 2;
        int minY = 2;
        int maxX = cellSize.width - BSPConfig.roomPad - xSize;
        int maxY = cellSize.height - BSPConfig.roomPad - ySize;

        newRoom.x = random.genrand_N(maxX - BSPConfig.roomPad + 1) + BSPConfig.roomPad;
        newRoom.y = random.genrand_N(maxY - BSPConfig.roomPad + 1) + BSPConfig.roomPad;
        //offset
        newRoom.x += cellSize.x;
        newRoom.y += cellSize.y;
        newRoom.width = xSize;
        newRoom.height = ySize;

        newRoom.UpdateRectangle();
        myRoom = newRoom;
        //if (parent != null) parent.AddRoom(newRoom);
        AddRoom(newRoom);
    }

}
